import configparser
import os

FILE_NAME = 'file_cfg.txt'
ENCODING = 'utf-8'

PRELOAD_STR = '''
[userinfo]
name = sky-风一样的男子
pwd = abc

[study]
python = 10
java = 20
linux = 30
'''


class StudentInfo(object):
    def __init__(self, file):
        self.__file = file
        # 初始化，主要用途是配置文件
        self.__cfg = configparser.ConfigParser()

    # 往配置文件里面写入内容
    def preload(self):
        if os.access(self.__file, os.F_OK):
            os.remove(self.__file)
        fd = open(self.__file, 'w')
        fd.writelines(PRELOAD_STR)
        fd.close()

    # 将配置文件内容加载到cfg
    def cfg_load(self):
        self.preload()
        self.__cfg.read(self.__file)

    # 将配置文件内容读取出来
    def cfg_dump(self):
        list = self.__cfg.sections()
        print("-------------------->")

        for sec in list:
            # 打印section
            print(sec)
            # 打印section下的item
            print(self.__cfg.items(sec))
        print("<--------------------")

    # 针对section，添加一个item
    def add_item(self, section, key, value):
        self.__cfg.set(section, key, value)

    # 添加一个section
    def add_section(self, section):
        self.__cfg.add_section(section)

    # 针对section，删除一个item
    def del_item(self, section, key):
        self.__cfg.remove_option(section, key)

    # 删除一个section
    def del_section(self, section):
        self.__cfg.remove_section(section)

    # 针对section，设置一个item
    def set_item(self, section, key, value):
        self.__cfg.set(section, key, value)

    # 保存配置文件内容
    def save(self):
        fd = open(self.__file, 'w')
        self.__cfg.write(fd)
        fd.close()


if __name__ == '__main__':
    info = StudentInfo(FILE_NAME)
    # 首先加载原始文件并显示
    info.cfg_load()
    info.cfg_dump()
    # 修改密码
    info.set_item('userinfo', 'pwd', '123456')
    # 添加一个section
    info.add_section('login_time')
    # 添加一个item
    info.add_item('login_time', '2019-02-07', '10minutes')
    info.cfg_dump()
    # 删除一个item
    info.del_item('study', 'java')
    info.cfg_dump()
    # 修改后的数据保存到文件
    info.save()
